/////////////////////
// Configuration
/////////////////////

var effective_date = '20070101';


String.prototype.trim = function () {
    return this.replace(
        /^\s*(\S*(\s+\S+)*)\s*$/, "$1"); 
}; 

function $(id) {
	return document.getElementById(id);
}

var schedule;
var day = (new Date()).getDay();

window.onload = function () {

	getURLXHR(getScheduleURL());

	$('flipBack').onclick = showBack;
	$('flipFront').onclick = showFront;
	$('front').onmouseover = showFlip;
	$('front').onmouseout = hideFlip;
	
	$('flipBack').onmouseover = function () {
		$('fliprollie').style.opacity = .25;
		};
	
	$('flipBack').onmouseout = function () {
		$('fliprollie').style.opacity = 0;
		};
	
	$('line').onchange = function () {
		$('station').options.length = 0;
		getURLXHR(getScheduleURL());
		};

	$('direction').onchange = function () {
		$('station').options.length = 0;
		getURLXHR(getScheduleURL());
		};

	$('effective_date').innerHTML = effective_date;

	};

function showFlip() {
	$('flipBack').style.opacity = 1;
}

function hideFlip() {
	$('flipBack').style.opacity = 0;
	$('fliprollie').style.opacity = 0;
}

function showBack() {
	setTimeout("$('front').style.display = 'none'",0);
	setTimeout("$('back').style.display = 'block'",0);
	if(window.widget){
		widget.resizeAndMoveTo (window.screenX, window.screenY, 315, 160);
		widget.prepareForTransition("ToBack");
		setTimeout("widget.performTransition();", 0);
    }
}

function showFront() {
	setTimeout("$('front').style.display = 'block'",0);
	setTimeout("$('back').style.display = 'none'",0);
	if(window.widget){
		setTimeout("widget.resizeAndMoveTo (window.screenX, window.screenY, 315, 73)",0);
		widget.prepareForTransition("ToFront");
		setTimeout("widget.performTransition();", 0);
    }
	updatePrefs();
}

var req;
var scheduleStr = "";
var station = "SANT CLRA";
var direction = "North";

function getURLXHR(url) {
	req = new XMLHttpRequest();
	req.onload = function (e, r) {
	}
	req.overrideMimeType("text/plain");
	req.open("GET", url);
	req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	req.setRequestHeader("Cache-Control", "no-cache");
	var params = "";
	req.send(params);
	req.onreadystatechange = processReqChange;
}

function processReqChange() {
    if (req.readyState == 4) {
        if (req.status == 200) {
			updateCmd();
        } else {
            alert("There was a problem retrieving the data:\n" + req.status);
        }
    }
}

function updateCmd() {
	timeArr = null;
	stationHash = null;
	stationNum = 0;
	timeTableArr = [];
	selectedStation = "";
	rows = 0;
	
	scheduleStr = req.responseText;
	schedule = getSchedule();
	parseData();
	getSelectedStation();
	update();
}

var currDate = new Date();

var timeArr;
var stationHash;
var stationNum = 0;
var timeTableArr = [];
var selectedStation;
var rows = 0;

function getScheduleURL() {
	
	var line = $('line').value;
	var direction = $('direction').value;
	var period = (currDate.getDay() == 6 ? 'SA' : (currDate.getDay() == 0 ? 'SU' : 'WK'));
	
	var url = 'http://www.vta.org/schedules/tdl/SC_' + line + direction + '_' + period + '_eff' + effective_date + '.tdl';

	return(url);
}

function getSchedule() {
	$('location').innerHTML = "Downloading schedules from VTA server.";
	$('arrivalTime').innerHTML = "";
	
	return scheduleStr;
}

function getSelectedStation() {
	station = $('station').value;
	selectedStation = station;
	for (var name in stationHash) {
		if (stationHash.hasOwnProperty(name)) {
			if(stationHash[name].name.trim()==station.trim()) {
				selectedStation = name;
			}
		}
	}
}

function updatePrefs() {
	getURLXHR(getScheduleURL());
}

var dataError;

function update() {
	if (stationHash[selectedStation]) {
		$('location').innerHTML = 
			stationHash[selectedStation].name.trim().replace(/ +(Light Rail|Lr|Station|Transit C).*/,"")
		 	+ ", " + ($('direction').value == 'NO' ? 'Northbound' : 'Southbound');
		$('arrivalTime').innerHTML = getMinUntil() + " min until next train";
	} else {
		if (dataError) {
			$('location').innerHTML = "Could not load data from VTA server.";
			$('arrivalTime').innerHTML = "";
		} else {
			$('location').innerHTML = "Station is not on selected line.";
			$('arrivalTime').innerHTML = "";
		}
	}
	var newDay = (new Date()).getDay();
	if (day!=newDay)
		updateCmd();
	setTimeout("update()",20000);
}

function getURL(str) {
	var url = new URL();
	var urlData = url.fetch(str);
	return urlData;
}

function parseData() {
	if (schedule=="Could not load URL") {
		dataError = true;
	}
	if (schedule) {
		var stationStr = schedule.substring(schedule.search(/[A-Z]{3}/g),schedule.search(/\n\n[A-Z]{3}/g));
		stationStr = stationStr.split("\n");
		var stationArr = stationStr.slice(0,stationStr.length);
		stationHash = [];
		for (var i=0;i<stationArr.length;i++) {
			var stn = stationArr[i].split("\t");
			if (stn[1]) {	
				stationHash[stn[0]] = { "name" : stn[1].trim().replace("Sta.","Station").replace("Ctr.","Center").replace("Lr Station","Light Rail Station"), "i" : i };
				// Dynamically add stations to station menu
				if ($('station').length<stationArr.length) {
					var stationInput = document.createElement("option");
					var stationText = document.createTextNode(stationHash[stn[0]].name);
					stationInput.appendChild(stationText);
					stationInput.value = stn[0];
					$('station').appendChild(stationInput);
				}
			}
			stationNum++;
		}
		
		var timesStr = schedule.substring(schedule.search(/\t\n/g),schedule.length);
		timesStr = timesStr.split("\t");
		timeArr = timesStr.slice(1,timesStr.length-1);
		
		var rowNum = timeArr.length/stationNum;
		rows = rowNum;
		
		for (var i=0;i<stationNum;i++) {
			var timeCol = [];
			for (var row=0;row<rowNum;row++) {
				timeCol.push(timeArr[row*stationNum+i]);
			}
			timeTableArr.push(timeCol);
		}
	} else {
		$('location').innerHTML = "Could not get data.";
		$('arrivalTime').innerHTML = "";
	}
}

function getMinUntil() {
	var posTime = Number.MIN_VALUE;
	var currTime = new Date();
	
	var mins = 0;
	for (var j=0;j<rows;j++) {
		if (posTime==Number.MIN_VALUE) {
			var timeStr = timeTableArr[stationHash[selectedStation].i][j];
			
			if (timeStr.length>1) {
				var timeArr = timeStr.split(":");
				if(timeStr.indexOf("A")!=-1) {
					timeArr[0] = parseInt(timeArr[0]);
					timeArr[1] = parseInt(timeArr[1].replace("A",""),10);
				}
				if(timeStr.indexOf("P")!=-1) {
					if (timeArr[0]!=12)
						timeArr[0] = parseInt(timeArr[0])+12;
					timeArr[1] = parseInt(timeArr[1].replace("P",""),10);
				}
				
				var arrive = new Date();
				arrive.setHours(timeArr[0]);
				arrive.setMinutes(timeArr[1]);
				
				timeUntil = arrive - currTime;
				mins = Math.round(timeUntil/(1000*60));
			}
		}
		if (mins>0&&posTime==Number.MIN_VALUE) {
			posTime = +mins;
		}
	}
	
	return posTime;
}

function populateStation() {
	var line = $('line').value;
	
	$('station').options.length = 0;
	
	if(line == '900') {
		
	} else if(line == '901') {
	} else if(line == '902') {
	}
	
}

